#include"Mylist.h"

List* GetList()
{
	List* ret = (List*)malloc(sizeof(List));
	ret->head = (Node*)malloc(sizeof(Node));

	if(ret  == NULL || ret->head == NULL)
	{
		perror("GetList->malloc");
		exit(-1);
	}
	ret->head->next = ret->head;
	ret->head->prev = ret->head;
	return ret;
}

Node* CreatNode( type val)
{
	Node* newnode = (Node*)malloc(sizeof(Node));

	if(newnode == NULL)
	{
		perror("CreatNode->malloc");
		exit(-1);
	}
	newnode->next = NULL;
	newnode->prev = NULL;
	newnode->val = val;
	return newnode;
}

int Empty(List* list)
{
	return list->head->next == list->head;
}

void PushPos(Node* pos, type val)
{
	Node* newnode  = CreatNode(val);
	pos->next->prev = newnode;
	newnode->next = pos->next;
	pos->next = newnode;
	newnode->prev = pos;
}

void PushFront(List* list, type val)
{
	PushPos(list->head, val);
}

void PushBack(List* list, type val)
{
	PushPos(list->head->prev, val);
}

void Destroy(List* list)
{
	Node* delnode = list->head->next;
	Node* tmp = NULL;
	while(delnode != list->head)
	{
		tmp = delnode->next;
        free(delnode);
		delnode = tmp;
	}
	free(list->head);
	free(list);
	list = NULL;
}

void PopBack(List* list)
{
     if(Empty(list))
	 {
        printf("list is no empty!");
	 }
	 else
	 {
		PopPos(list->head->prev);
	 }
}
void PopPos(Node* pos)
{
	if(pos == NULL)
	{
       perror("pos == NULL");
	   exit(-1);
	}
	Node* a = pos->prev;
	Node* c = pos->next;
	Node* b = pos;
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	pos->next = NULL;
	pos->prev = NULL;

	free(pos);
    pos = NULL;
}